import {getType} from './tools'
import {Encrypt, Decrypt} from './crypto'

export default class Storage {
  constructor({mode, prefix}) {
    this.mode = mode || 'sessionStorage'
    this.prefix = prefix + '_' || ''
    this.store = window[this.mode]
  }

  isSupport() {
    if (!window[this.mode]) {
      getType(1)
      throw new Error(`浏览器不支持${this.mode}`)
    } else {
      console.log('支持')
    }
  }

  setPreName(key) {
    return this.prefix + key
  }

  // 存
  save(key, value, time, mode) {
    let store = mode ? window[mode] : this.store

    // 获取过期时间
    let expiresTime = new Date().getTime() + Number(time)

    // 包装数据
    let saveObj = {value}

    // 放入过期时间
    if (time) saveObj.expiresTime = expiresTime

    store.setItem(this.setPreName(key), Encrypt(JSON.stringify(saveObj)))
  }

  // 存多个
  saveList(list, mode) {
    list.forEach(item => {
      this.save(item.key, item.value, item.time, mode)
    })
  }

  // 取
  get(key, mode) {
    let store = mode ? window[mode] : this.store

    let getStorageItem = JSON.parse(
      Decrypt(store.getItem(this.setPreName(key)))
    )

    if (!getStorageItem) { // 找不到返回null
      return null
    } else if (getStorageItem.expiresTime &&
      new Date().getTime() > getStorageItem.expiresTime) { // 查看是否过期

      // 过期删除value
      // this.save(key, '过期', '', mode)

      // 返回null
      return '过期'
    } else {
      return getStorageItem.value
    }
  }

  // 删
  delete(key, mode) {
    let store = mode ? window[mode] : this.store

    store.removeItem(this.setPreName(key))
  }

  // 用于删除部分数据，参数为一个数组，存储的为需要删除的key列表
  deletePartStorage(storageList, mode) {
    storageList.forEach((key) => {
      this.delete(key, mode)
    })
  }

  // 全删
  deleteAll(model) {
    let store = mode ? window[mode] : this.store

    store.removeItem(this.setPreName(key))
  }

}
